﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;

namespace Reborn_WorldServer.TransferCharacters
{
    public class TransferCharacterManagerWS
    {
        private List<TransferCharacterRequestWS> transferRequests = new List<TransferCharacterRequestWS>();

        public TransferCharacterManagerWS() { }

        public bool SendTransferRequest(TransferCharacterRequestWS newRequest)
        {
            lock (transferRequests)
            {
                foreach (TransferCharacterRequestWS request in transferRequests)
                {
                    if (request.character.UserID == newRequest.character.UserID)
                        return false;
                }
                transferRequests.Add(newRequest);
            }

            StringWriter stringWriter = new StringWriter();
            XmlTextWriter xmldoc = new XmlTextWriter(stringWriter);

            xmldoc.WriteStartElement("transfercharacter");

            xmldoc.WriteAttributeString("userid", newRequest.character.UserID.ToString());
            xmldoc.WriteAttributeString("characterid", newRequest.character.ID.ToString());
            xmldoc.WriteAttributeString("mapid", newRequest.MapID.ToString());
            xmldoc.WriteAttributeString("instance", newRequest.Instance.ToString());
            xmldoc.WriteAttributeString("mapx", newRequest.MapX.ToString());
            xmldoc.WriteAttributeString("mapy", newRequest.MapY.ToString());

            xmldoc.WriteEndElement();

            xmldoc.Flush();
            xmldoc.Close();

            stringWriter.Flush();

            string xmlMessage = stringWriter.ToString();

            Managers.BeginSendToPrimary(xmlMessage);
            
            return true;
        }

        public void TransferCharacterTimeout(TransferCharacterRequestWS request)
        {
            lock (transferRequests)
            {
                if (transferRequests.Contains(request))
                {
                    transferRequests.Remove(request);
                    request.processResult("Map is currently unavailable", "", -1);
                }
            }
        }
        public void ProcessTransferCharacterResult(int userID, string error, string uid, int port)
        {
            lock (transferRequests)
            {
                foreach (TransferCharacterRequestWS transferRequest in transferRequests)
                {
                    if (transferRequest.character.UserID == userID)
                    {
                        transferRequests.Remove(transferRequest);
                        transferRequest.processResult(error, uid, port);
                        break;
                    }
                }
            }
        }
    }
}
